﻿using Common;
using DBUtility;
using DeliveryManage.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using System.Security.Cryptography;
using System.Runtime.CompilerServices;
using DeliveryManage.Model;

namespace DeliveryManage.Controllers
{
    public class DataController : BaseController
    {
        // GET: Data
        protected int totalCount;
        protected int page;
        protected int pageSize;
        #region 返回新闻每页数量=========================
        private int GetPageSize(int _default_size, string CookieName)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie(CookieName, "FxManage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        #region 我的业绩
        /// <summary>
        /// 我的业绩（员工）
        /// </summary>
        /// <returns></returns>
        public ActionResult MyPerformance()
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            string action = DTRequest.GetQueryString("action");
            if (!ChkAdminLevels("MyPerformance", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            DeliveryManage.Model.Sys_User nowUser = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            DeliveryManage.DAL.Pro_Orders orderDal = new DAL.Pro_Orders();
            //获取业绩提成给规则
            DeliveryManage.DAL.Sys_PerformanceRules rulesDal = new DAL.Sys_PerformanceRules();
            List<DeliveryManage.Model.Sys_PerformanceRules> Rules = rulesDal.GetModelByType(nowUser.IsBasicSalary ? 1 : 0);

            //获取所有订单信息
            string where = string.Format("EmployeeId = {0} and Status in ({1},{2})", nowUser.Id, (int)DTEnums.EnumOrderState.AuditSuccess, (int)DTEnums.EnumOrderState.FinishOrder);
            List<DeliveryManage.Model.Pro_Orders> allOrderList = orderDal.GetAllOrderList(where);

            //获取本日业绩数据
            EmployeePerformance todayPerformance = new EmployeePerformance();
            todayPerformance.Employee = nowUser.Id;
            todayPerformance.EmployeeName = nowUser.Nickname;
            DateTime todayDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            ///提交时间大于今天且审核通过的订单数据
            List<DeliveryManage.Model.Pro_Orders> todayOrderList = allOrderList.Where(x => x.Created > todayDate).ToList();
            todayPerformance.TotalFinalAmount = todayOrderList.Where(p=> p.TotalAmount != 19).Sum(p => p.TotalAmount);
            todayPerformance.AddOrderNum = todayOrderList.Count();
            todayPerformance.EmployeeType = nowUser.IsBasicSalary;
            todayPerformance.NewOrderNum = todayOrderList.Where(p => p.OrderType == false).Count();
            todayPerformance.RepurchaseOrder = todayOrderList.Where(p => p.OrderType == true).Count();
            todayPerformance.NewOrderAmount = todayOrderList.Where(p => p.OrderType == false && p.TotalAmount != 19).Sum(p => p.TotalAmount);
            todayPerformance.RepurchaseOrderAmount = todayOrderList.Where(p => p.OrderType == true && p.TotalAmount != 19).Sum(p => p.TotalAmount);
            todayPerformance.GiftFrequency = todayOrderList.Where(p => p.TotalAmount == 19).Count();
            //foreach (DeliveryManage.Model.Pro_Orders order in todayOrderList)
            //{
            //    todayPerformance.TotalGoodsAmount += order.OrderGoods.Sum(a => a.GoodsAmount);
            //    todayPerformance.TotalFreight += order.OrderGoods.Sum(a => a.Freight);
            //    todayPerformance.TotalAddPrice += order.OrderGoods.Sum(a => a.AddPrice);
            //}
            //计算今日业绩
            if (todayPerformance.TotalFinalAmount == 0)
            {
                todayPerformance.MyPerformanceAmount = 0;
            }
            else
            {
                foreach (DeliveryManage.Model.Sys_PerformanceRules rule in Rules)
                {
                    if (rule.MinLimit <= todayPerformance.TotalFinalAmount && rule.MaxLimit >= todayPerformance.TotalFinalAmount)
                    {
                        todayPerformance.MyPerformanceAmount = (decimal)Math.Round(Convert.ToDouble(todayPerformance.TotalFinalAmount * rule.CommRatio / 100M), 2);
                        break;
                    }
                }
            }
            ViewBag.TodayPerformance = todayPerformance;
            //获取本月业绩数据
            EmployeePerformance MonthPerformance = new EmployeePerformance();
            MonthPerformance.Employee = nowUser.Id;
            MonthPerformance.EmployeeName = nowUser.Nickname;
            DateTime firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            ///提交时间大于今天且审核通过的订单数据
            List<DeliveryManage.Model.Pro_Orders> MonthOrderList = allOrderList.Where(x => x.Created > firstDayOfMonth && x.Created < firstDayOfMonth.AddMonths(1)).ToList();
            MonthPerformance.TotalFinalAmount = MonthOrderList.Where(p => p.TotalAmount != 19).Sum(p => p.TotalAmount);
            MonthPerformance.AddOrderNum = MonthOrderList.Count();
            MonthPerformance.EmployeeType = nowUser.IsBasicSalary;
            MonthPerformance.NewOrderNum = MonthOrderList.Where(p => p.OrderType == false).Count();
            MonthPerformance.RepurchaseOrder = MonthOrderList.Where(p => p.OrderType == true).Count();
            MonthPerformance.NewOrderAmount = MonthOrderList.Where(p => p.OrderType == false && p.TotalAmount != 19).Sum(p => p.TotalAmount);
            MonthPerformance.RepurchaseOrderAmount = MonthOrderList.Where(p => p.OrderType == true && p.TotalAmount != 19).Sum(p => p.TotalAmount);
            MonthPerformance.GiftFrequency = MonthOrderList.Where(p => p.TotalAmount == 19).Count();
            //foreach (DeliveryManage.Model.Pro_Orders order in MonthOrderList)
            //{
            //    MonthPerformance.TotalGoodsAmount += order.OrderGoods.Sum(a => a.GoodsAmount);
            //    MonthPerformance.TotalFreight += order.OrderGoods.Sum(a => a.Freight);
            //    MonthPerformance.TotalAddPrice += order.OrderGoods.Sum(a => a.AddPrice);
            //}
            //计算本月业绩
            if (MonthPerformance.TotalFinalAmount == 0)
            {
                MonthPerformance.MyPerformanceAmount = 0;
            }
            else
            {
                foreach (DeliveryManage.Model.Sys_PerformanceRules rule in Rules)
                {
                    if (rule.MinLimit <= MonthPerformance.TotalFinalAmount && rule.MaxLimit >= MonthPerformance.TotalFinalAmount)
                    {
                        MonthPerformance.MyPerformanceAmount = (decimal)Math.Round(Convert.ToDouble(MonthPerformance.TotalFinalAmount * rule.CommRatio / 100M), 2);
                        break;
                    }
                }
            }
            ViewBag.MonthPerformance = MonthPerformance;
            return View();
        }
        #endregion

        #region 团队业绩
        public ActionResult TeamPerformance() 
        {
            ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 200, msg = "允许执行该操作的权限，操作成功！" };
            string action = DTRequest.GetQueryString("action");
            if (!ChkAdminLevels("TeamPerformance", DTEnums.ActionEnum.View.ToString()))
            {
                ViewBag.ReturnMsgModel = new ReturnMsgModel { code = 400, msg = "您没有执行该操作的权限，操作失败！" };
                return View();
            }; //检查权限
            int userid = 0;
            this.pageSize = GetPageSize(DTRequest.GetQueryInt("pageSize", 10), "pageSize");
            this.page = DTRequest.GetQueryInt("page", 1);
            userid = DTRequest.GetQueryInt("uid");
            int toType = DTRequest.GetQueryInt("totype", -1);
            string startdate = DTRequest.GetQueryString("startdate");
            string enddate = DTRequest.GetQueryString("enddate");
            if (userid <= 0)
            {
                DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                userid = model.Id;
            }

            ViewData["SelectUser"] = userid;
            ViewData["pageSize"] = this.pageSize;
            ViewData["page"] = this.page;
            #region 搜索
            string where = string.Format("Status= 1 and TopUser={0}", userid);
            if (toType > -1)
            {
                where += " and IsBasicSalary=" + toType;
                ViewData["toType"] = toType;
            }
            #endregion
            #region 未传入日期默认获取当月数据
            if (string.IsNullOrEmpty(startdate))
            {
                startdate = DateTime.Now.Year + "-" + DateTime.Now.Month + "-01";
                enddate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).ToString("yyyy-MM-dd");
            }
            else if (string.IsNullOrEmpty(enddate)) {
                DateTime startDate = Convert.ToDateTime(startdate);
                enddate = new DateTime(startDate.Year, startDate.Month, 1).AddMonths(1).ToString("yyyy-MM-dd");
            }
            ViewData["Startdate"] = startdate;
            ViewData["Enddate"] = enddate;
            #endregion
            List<DeliveryManage.Model.Sys_User> userlist = new List<DeliveryManage.Model.Sys_User>();
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            userlist = dal.GetQueryList(this.pageSize, this.page, where, "Id asc", out this.totalCount);
            List<EmployeePerformance> PerformanceList = new List<EmployeePerformance>();
            //依次计算员工业绩
            if (userlist != null && userlist.Count > 0) {
                DeliveryManage.DAL.Pro_Orders orderDal = new DAL.Pro_Orders();
                DeliveryManage.DAL.Sys_PerformanceRules rulesDal = new DAL.Sys_PerformanceRules();
                List<DeliveryManage.Model.Sys_PerformanceRules> Rules = rulesDal.GetModelByType(-1);
                foreach (var item in userlist)
                {
                    //获取业绩提成给规则
                    List<DeliveryManage.Model.Sys_PerformanceRules> userRules = Rules.Where(p=>p.ToType == (item.IsBasicSalary?1:0)).ToList();
                    DateTime firstDayOfMonth = Convert.ToDateTime(startdate);
                    DateTime endDayOfMonth = Convert.ToDateTime(enddate);
                    ///提交时间位于区间且审核通过的订单数据
                    string orderWhere = string.Format("EmployeeId = {0} and Status in ({1},{2}) and Created > '{3}' and Created < '{4}'", item.Id, (int)DTEnums.EnumOrderState.AuditSuccess,
                        (int)DTEnums.EnumOrderState.FinishOrder, firstDayOfMonth, endDayOfMonth);
                    List<DeliveryManage.Model.Pro_Orders> MonthOrderList = orderDal.GetAllOrderList(orderWhere);

                    //获取区间业绩数据
                    EmployeePerformance MonthPerformance = new EmployeePerformance();
                    MonthPerformance.Employee = item.Id;
                    MonthPerformance.EmployeeName = item.Nickname;
                    MonthPerformance.TotalFinalAmount = MonthOrderList.Where(p => p.TotalAmount != 19).Sum(p => p.TotalAmount);
                    MonthPerformance.AddOrderNum = MonthOrderList.Count();
                    MonthPerformance.EmployeeType = item.IsBasicSalary;
                    MonthPerformance.NewOrderNum = MonthOrderList.Where(p => p.OrderType == false).Count();
                    MonthPerformance.RepurchaseOrder = MonthOrderList.Where(p => p.OrderType == true).Count();
                    MonthPerformance.NewOrderAmount = MonthOrderList.Where(p => p.OrderType == false && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                    MonthPerformance.RepurchaseOrderAmount = MonthOrderList.Where(p => p.OrderType == true && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                    MonthPerformance.GiftFrequency = MonthOrderList.Where(p => p.TotalAmount == 19).Count();
                    //foreach (DeliveryManage.Model.Pro_Orders order in MonthOrderList)
                    //{
                    //    MonthPerformance.TotalGoodsAmount += order.OrderGoods.Sum(a => a.GoodsAmount);
                    //    MonthPerformance.TotalFreight += order.OrderGoods.Sum(a => a.Freight);
                    //    MonthPerformance.TotalAddPrice += order.OrderGoods.Sum(a => a.AddPrice);
                    //}
                    //计算业绩提成
                    if (MonthPerformance.TotalFinalAmount == 0)
                    {
                        MonthPerformance.MyPerformanceAmount = 0;
                    }
                    else
                    {
                        foreach (DeliveryManage.Model.Sys_PerformanceRules rule in userRules)
                        {
                            if (rule.MinLimit <= MonthPerformance.TotalFinalAmount && rule.MaxLimit >= MonthPerformance.TotalFinalAmount)
                            {
                                MonthPerformance.MyPerformanceAmount = (decimal)Math.Round(Convert.ToDouble(MonthPerformance.TotalFinalAmount * rule.CommRatio / 100M), 2);
                                break;
                            }
                        }
                    }
                    PerformanceList.Add(MonthPerformance);
                }
            }

            ListItemCollection Statusitem = new ListItemCollection();
            Statusitem.Add(new ListItem("全部员工", "-1"));
            Statusitem.Add(new ListItem("有底薪", "1"));
            Statusitem.Add(new ListItem("无底薪", "0"));
            ViewData["ToTypeList"] = new SelectList(Statusitem, "value", "text");
            ViewData["Startdate"] = startdate;
            ViewData["Enddate"] = enddate;
            ViewBag.PerformanceList = PerformanceList;
            //绑定页码
            string pageUrl = Utils.CombUrlTxt("/Data/TeamPerformance", "page={0}&pageSize={1}&totype={2}&startdate={3}&enddate={4}&uid={5}", "__id__", pageSize.ToString(), toType.ToString(),startdate, enddate, userid.ToString());
            ViewBag.PageInnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 10);
            return View();
        }

        [HttpPost]
        public JsonResult ExportTeamPerformance()
        {
            try
            {
                string sheetName = "员工业绩明细列表";

                #region 查询并构建数据
                int uid = DTRequest.GetFormInt("uid", 0);
                int toType = DTRequest.GetQueryInt("totype", -1);
                string startdate = DTRequest.GetFormString("startdate");
                string enddate = DTRequest.GetFormString("enddate");

                DeliveryManage.Model.Sys_User u = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                if (uid == 0)
                {
                    uid = u.Id;
                }
                string where = string.Format("Status= 1 and TopUser={0}", uid);
                if (toType > -1)
                {
                    where += " and IsBasicSalary=" + toType;
                }
                ///未传入日期默认获取当月数据
                if (string.IsNullOrEmpty(startdate))
                {
                    startdate = DateTime.Now.Year + "-" + DateTime.Now.Month + "-01";
                    enddate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).ToString("yyyy-MM-dd");
                }
                else if (string.IsNullOrEmpty(enddate))
                {
                    DateTime startDate = Convert.ToDateTime(startdate);
                    enddate = new DateTime(startDate.Year, startDate.Month, 1).AddMonths(1).ToString("yyyy-MM-dd");
                }
                List<DeliveryManage.Model.Sys_User> userlist = new List<DeliveryManage.Model.Sys_User>();
                DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
                userlist = dal.GetTuiList(where);
                List<EmployeePerformance> PerformanceList = new List<EmployeePerformance>();
                //依次计算员工业绩
                if (userlist != null && userlist.Count > 0)
                {
                    DeliveryManage.DAL.Pro_Orders orderDal = new DAL.Pro_Orders();
                    DeliveryManage.DAL.Sys_PerformanceRules rulesDal = new DAL.Sys_PerformanceRules();
                    List<DeliveryManage.Model.Sys_PerformanceRules> Rules = rulesDal.GetModelByType(-1);
                    foreach (var item in userlist)
                    {
                        //获取业绩提成给规则
                        List<DeliveryManage.Model.Sys_PerformanceRules> userRules = Rules.Where(p => p.ToType == (item.IsBasicSalary ? 1 : 0)).ToList();
                        DateTime firstDayOfMonth = Convert.ToDateTime(startdate);
                        DateTime endDayOfMonth = Convert.ToDateTime(enddate);
                        ///提交时间位于区间且审核通过的订单数据
                        string orderWhere = string.Format("EmployeeId = {0} and Status in ({1},{2}) and Created > '{3}' and Created < '{4}'", item.Id, (int)DTEnums.EnumOrderState.AuditSuccess,
                            (int)DTEnums.EnumOrderState.FinishOrder, firstDayOfMonth, endDayOfMonth);
                        List<DeliveryManage.Model.Pro_Orders> MonthOrderList = orderDal.GetAllOrderList(orderWhere);

                        //获取区间业绩数据
                        EmployeePerformance MonthPerformance = new EmployeePerformance();
                        MonthPerformance.Employee = item.Id;
                        MonthPerformance.EmployeeName = item.Nickname;
                        MonthPerformance.TotalFinalAmount = MonthOrderList.Where(p=> p.TotalAmount != 19).Sum(p => p.TotalAmount);
                        MonthPerformance.AddOrderNum = MonthOrderList.Count();
                        MonthPerformance.EmployeeTypeStr = item.IsBasicSalary ? "有" : "无";
                        MonthPerformance.NewOrderNum = MonthOrderList.Where(p => p.OrderType == false).Count();
                        MonthPerformance.RepurchaseOrder = MonthOrderList.Where(p => p.OrderType == true).Count();
                        MonthPerformance.NewOrderAmount = MonthOrderList.Where(p => p.OrderType == false && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                        MonthPerformance.RepurchaseOrderAmount = MonthOrderList.Where(p => p.OrderType == true && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                        MonthPerformance.GiftFrequency = MonthOrderList.Where(p => p.TotalAmount == 19).Count();
                        //计算业绩提成
                        if (MonthPerformance.TotalFinalAmount == 0)
                        {
                            MonthPerformance.MyPerformanceAmount = 0;
                        }
                        else
                        {
                            foreach (DeliveryManage.Model.Sys_PerformanceRules rule in userRules)
                            {
                                if (rule.MinLimit <= MonthPerformance.TotalFinalAmount && rule.MaxLimit >= MonthPerformance.TotalFinalAmount)
                                {
                                    MonthPerformance.MyPerformanceAmount = (decimal)Math.Round(Convert.ToDouble(MonthPerformance.TotalFinalAmount * rule.CommRatio / 100M), 2);
                                    break;
                                } 
                            }
                        }
                        PerformanceList.Add(MonthPerformance);
                    }
                }
                #endregion
                if (PerformanceList != null && PerformanceList.Count > 0)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("EmployeeName", "员工姓名");
                    dic.Add("EmployeeTypeStr", "有无底薪");
                    dic.Add("TotalFinalAmount", "总业绩(元)");
                    dic.Add("NewOrderAmount", "新单业绩(元)");
                    dic.Add("RepurchaseOrderAmount", "复购业绩(元)");
                    dic.Add("AddOrderNum", "完成单量(个)");
                    dic.Add("NewOrderNum", "完成新单(个)"); 
                    dic.Add("RepurchaseOrder", "完成复购(个)");
                    dic.Add("GiftFrequency", "送酒次数(次)"); 
                    dic.Add("MyPerformanceAmount", "业绩提成(元)");
                    string downurl = ExcelHelper.EntityListToExcel2003(dic, PerformanceList, sheetName);
                    string FilePath = HttpContext.Request.UrlReferrer.Authority + "/" + downurl;
                    return Json(new ReturnMsgModel { status = true, msg = "导出成功！", data = FilePath });
                }
                else
                {
                    return Json(new ReturnMsgModel { status = false, msg = "没有相关数据！" });
                }
            }
            catch (Exception e)
            {
                var a = e.Message;
                return Json(new ReturnMsgModel { status = false, msg = "导出失败！" });
            }
        }
        #endregion

        #region 员工业绩提成计算

        #endregion
    } 
}